# usage_crud.py
from typing import List
from sqlalchemy.orm import Session
from ..models.usage_model import Usage
from datetime import date
from sqlalchemy import func
from fastapi import HTTPException

def get_usage_by_date(db: Session, data: date) -> List[Usage]:
    result=db.query(Usage).filter(Usage.data == data).all()
    if not result:
        # raise HTTPException(status_code=404, detail="No usage found")
        return None
    usage_list = [usage.as_dict() for usage in result]
    return usage_list




def get_usage_by_date_range(db: Session, start_date: date, end_date: date) -> List[Usage]:

    result=db.query(Usage).filter(
        Usage.data >= start_date,
        Usage.data <= end_date
    ).all()
    if not result:
        raise HTTPException(status_code=404, detail="No usage found")
    return [usage.as_dict() for usage in result]

def get_questions_quantity(db: Session):
    """
       获取数据库中所有记录的 questions_quantity 字段的总和
       """
    total = db.query(Usage).with_entities(
        func.sum(Usage.questions_quantity)
    ).scalar()

    # 如果结果为 None（即没有数据），返回 0
    return total if total is not None else 0

def get_usage_by_date_and_user(db: Session, data: date, user_id: int) -> Usage:

    return db.query(Usage).filter(
        Usage.data == data,
        Usage.user_id == user_id
    ).first()
